package com.mh.exception;

import com.alibaba.fastjson.JSON;
import com.mh.common.ResponseResult;
import com.mh.utils.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//自定义授权异常处理,实现AccessDeniedHandler接口
//AccessDeniedHandler: 用于处理已认证用户访问受保护资源时权限不足的异常
@Component
public class AccessDeniedHandlerImpl implements AccessDeniedHandler {
    @Override
    //当用户已通过认证但权限不足时，Spring Security会调用handle方法
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        ResponseResult result = new ResponseResult(HttpStatus.FORBIDDEN.value(), "权限不足禁止访问");
        String json = JSON.toJSONString(result);
        WebUtils.renderString(response, json);
    }
}
